<template>
  <div class="demo-search">
    <div class="search-controls">
      <el-input
        v-model="searchTerm"
        placeholder="搜索演示示例..."
        clearable
        class="search-input"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      
      <el-select
        v-model="selectedCategory"
        placeholder="选择分类"
        class="category-select"
      >
        <el-option
          v-for="category in categories"
          :key="category"
          :label="category === 'all' ? '所有分类' : category"
          :value="category"
        />
      </el-select>
    </div>
    
    <div class="search-info" v-if="searchTerm || selectedCategory !== 'all'">
      找到 {{ filteredDemos.length }} 个匹配的演示示例
    </div>
  </div>
</template>

<script>
import { ref, watch, computed } from 'vue';
import { Search } from '@element-plus/icons-vue';
import demoStore from '../store/demoStore.js';

export default {
  name: 'DemoSearch',
  components: {
    Search
  },
  setup() {
    const searchTerm = ref(demoStore.state.searchTerm);
    const selectedCategory = ref(demoStore.state.selectedCategory);
    
    // 获取所有分类
    const categories = computed(() => {
      const categories = [...new Set(demoStore.state.demos.map(demo => demo.category))];
      return ['all', ...categories];
    });
    
    // 获取过滤后的演示示例
    const filteredDemos = computed(() => {
      let filtered = demoStore.state.demos;
      
      // 根据分类过滤
      if (selectedCategory.value !== 'all') {
        filtered = filtered.filter(demo => demo.category === selectedCategory.value);
      }
      
      // 根据搜索词过滤
      if (searchTerm.value) {
        const term = searchTerm.value.toLowerCase();
        filtered = filtered.filter(demo => 
          demo.name.toLowerCase().includes(term) || 
          demo.description.toLowerCase().includes(term) ||
          demo.id.toLowerCase().includes(term)
        );
      }
      
      return filtered;
    });
    
    // 监听搜索词变化
    watch(searchTerm, (newTerm) => {
      demoStore.setSearchTerm(newTerm);
    });
    
    // 监听分类变化
    watch(selectedCategory, (newCategory) => {
      demoStore.setSelectedCategory(newCategory);
    });
    
    return {
      searchTerm,
      selectedCategory,
      categories,
      filteredDemos
    };
  }
};
</script>

<style scoped>
.demo-search {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
}

.search-controls {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.search-input {
  flex: 1;
}

.category-select {
  width: 150px;
}

.search-info {
  font-size: 12px;
  color: #909399;
  text-align: right;
}
</style>